package client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;

import service.ServerService;
import utility.CONST;
import utility.FileService;
import utility.DatagramService;
import data.Chunk;
import data.Packet;

public class UDPClient {
	
	public static Queue<Chunk> listChunk = new LinkedList<Chunk>();
	
	private String torrentPath;
	DatagramSocket clientSocket = null;
	DatagramPacket clientPacket = null;
	private Thread clientThread = null;
	private byte[] request = null;
	
	private int port = CONST.DEFAULT_PORT;
	
	public UDPClient(String torrentPath) {
		this.torrentPath = torrentPath;
		FileService service = new FileService();
		listChunk = service.readTorrentFileIntoApp(this.torrentPath);
		
		try {
			this.clientSocket = new DatagramSocket();
			this.start();
		} catch (SocketException e) {
			e.printStackTrace();
		}	
	}
	
	private void start() {
		clientThread = new Thread(new Runnable() {
			public void run() {
				request = new byte[1024];
				clientPacket = new DatagramPacket(request, request.length);
				while (listChunk.size() != 0) {
					try {
						clientSocket.receive(clientPacket);
						System.out.println("Client received!!");
				
						//ServerService serverService = new ServerService(serverPacket);
								
						//Thread t = new Thread(serverService);
						//t.start();
					} catch (IOException e) {
						e.printStackTrace();
						System.out.println(e.getMessage());
					}
				}
				System.out.println("Client end at " + new Date());
			}
		});
		clientThread.start();
	}
}
